package com.roadmap.biz.sns;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

import com.roadmap.biz.common.BaseManager;
import com.roadmap.common.BaseEntity;
import com.roadmap.entities.Visitor;
import com.roadmap.entities.ext.VisitorExt;
import com.roadmap.exception.ActionNotSupportedException;
import com.roadmap.exception.EntityNotFoundException;
import com.roadmap.exception.InvalidActionException;
import com.roadmap.exception.InvalidQueryException;
import com.roadmap.exception.InvalidStatusException;
import com.roadmap.exception.InvalidValueException;
import com.roadmap.exception.NotAuthorizedException;
import com.roadmap.exception.NotMatchedException;
import com.roadmap.exception.NullObjectException;
import com.roadmap.exception.ServerException;
import com.roadmap.repo.db.RdcQuery;

public class VisitorManager extends BaseManager {
	private final static int MAX_RESULTS_FOR_ASPIRANT_PAGE = 10;

	public VisitorManager(String currentUser, String itemOwner) {
		super(currentUser, itemOwner, Visitor.class);
	}

	@Override
	public void create(BaseEntity entity) throws NullObjectException,
			InvalidActionException, InvalidValueException, ServerException,
			EntityNotFoundException, ActionNotSupportedException,
			InvalidStatusException {
	
		checkEntityIsValid(entity);
		getDbUtil().saveOrUpdateEntity(entity);
	}

	/** 获取所有好友访问记录 */
	@Override
	public List getEntitiesOfOwner() throws ServerException,
			NullObjectException, NotMatchedException, InvalidValueException,
			InvalidQueryException {
		return getVistorRecords(-1);
	}

	/** 获取有限个好友访问记录 */
	@Override
	public List getExecutableEntities() throws HibernateException,
			ServerException, InvalidQueryException, InvalidValueException,
			NotMatchedException, ActionNotSupportedException {
		return getVistorRecords(MAX_RESULTS_FOR_ASPIRANT_PAGE);
	}

	private List<VisitorExt> getVistorRecords(int num) throws NullObjectException,
			InvalidQueryException, ServerException, InvalidValueException {
		String sql = "select {v.*}, a.realName from visitor as v, aspirant as a where v.hostId=:uid and v.visitorId=a.aspirantId order by visitTime DESC";
		RdcQuery query = getDbUtil().createNativeSQLQuery(sql);
		query.addEntity("v", Visitor.class);
		query.setParameter("uid", getOwnerId());
		query.addScalar("realName", Hibernate.STRING);
		if (num > 0) {
			query.setMaxResults(num);
		}
		List results = query.getResults();
		if (results == null || results.isEmpty()) {
			return null;
		}
		List<VisitorExt> visitors = new ArrayList<VisitorExt>();
		Iterator iter = results.iterator();
		while (iter.hasNext()) {
			Object[] result = (Object[]) iter.next();
			Visitor vs = (Visitor) result[0];
			VisitorExt ext = new VisitorExt(vs);
			ext.setName((String) result[1]);
			visitors.add(ext);
		}
		return visitors;
	}

}
